﻿namespace KnownCMS.Repositories;

class SiteRepository
{
    internal static Task<PagingResult<PostListInfo>> QueryPostsAsync(Database db, PagingCriteria criteria)
    {
        var sql = @"select a.*,b.NickName as Author 
from CmPost a 
left join CmUser b on b.UserName=a.CreateBy 
where 1=1";

        var key = criteria.Parameters.GetValue<string>("Key");
        if (!string.IsNullOrWhiteSpace(key))
        {
            sql += " and (a.Title like @Key or a.Content like @Key)";
            criteria.SetQuery("Key", $"%{key}%");
        }

        return db.QueryPageAsync<PostListInfo>(sql, criteria);
    }

    internal static Task<List<PostListInfo>> GetRankPostsAsync(Database db, ContentType type)
    {
        var sql = $"select * from CmPost where Type='{type}' order by RankNo desc limit 5 offset 0";
        return db.QueryListAsync<PostListInfo>(sql, type);
    }

    internal static Task<PagingResult<ReplyListInfo>> QueryRepliesAsync(Database db, PagingCriteria criteria)
    {
        var sql = "select * from CmReply where UserId=@UserId";

        var key = criteria.Parameters.GetValue<string>("Key");
        if (!string.IsNullOrWhiteSpace(key))
        {
            sql += " and Content like @Key";
            criteria.SetQuery("Key", $"%{key}%");
        }

        return db.QueryPageAsync<ReplyListInfo>(sql, criteria);
    }

    internal static async Task<bool> ExistsUserNameAsync(Database db, CmUser model)
    {
        var sql = "select count(*) from CmUser where Id<>@Id and UserName=@UserName";
        return await db.ScalarAsync<int>(sql, new { model.Id, model.UserName }) > 0;
    }
}